﻿using System;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Collections.Generic;

namespace CodeArt.SharePoint.Controls
{
    using CodeArt.SharePoint.Configuration;
    using CodeArt.SharePoint.Library;


    public class PickerSearchControl : SimpleQueryControl
    {
        PickerSearchDialog PickerSearchDialog
        {
            get { return (PickerSearchDialog)base.PickerDialog; }
        }

        public override PickerEntity GetEntity(DataRow entityDataRow)
        {
            if (entityDataRow == null)
            {
                throw new ArgumentNullException("entityDataRow");
            }
            string lookupField = PickerSearchDialog.Picker.PickerData.LookupField;
            string lpIDField = PickerSearchDialog.Picker.PickerData.PickerTemplate.ViewFields.LookupIDField;

            PickerEntity entity = new PickerEntity();
            object obj = entityDataRow[lpIDField];
            entity.Key = obj!= null ? obj.ToString():string.Empty;
            entity.IsResolved = true;

            obj = entityDataRow[lookupField];
            string text = obj != null ? obj.ToString() : string.Empty; ;

            entity.DisplayText = text;
            entity.Description = text;

            entity.EntityData.Clear();

            foreach (ViewFieldElement vField in PickerSearchDialog.Picker.PickerData.PickerTemplate.ViewFields.Fields)
            {
                entity.EntityData.Add(vField.Name, entityDataRow[vField.Name]);           
            }

            if (!entity.EntityData.ContainsKey(lpIDField))
                entity.EntityData.Add(lpIDField, entityDataRow[lpIDField]);

            string lpNameField = PickerSearchDialog.Picker.PickerData.PickerTemplate.ViewFields.LookupNameField;
            if (!entity.EntityData.ContainsKey(lpNameField))
                entity.EntityData.Add(lpNameField, entityDataRow[lpNameField]);

            if (!entity.EntityData.ContainsKey(lookupField))
              entity.EntityData.Add(lookupField, entityDataRow[lookupField]);

            return entity;
        }

        protected override void OnLoad(EventArgs e)
        {
            EnsureChildControls();
            // Populate filter column list          
            foreach (ViewFieldElement vfield in PickerSearchDialog.Picker.PickerData.PickerTemplate.ViewFields.Fields)
            {
                ColumnList.Items.Add(new ListItem(vfield.Value, vfield.Name));
            }
            base.OnLoad(e);
        }

        protected override int IssueQuery(
            string search, string groupName, int pageIndex, int pageSize)
        {
            DataTable resultsTable = new DataTable();

            //
            // 1. Create the result table columns
            //
            foreach (ViewFieldElement vfield in PickerSearchDialog.Picker.PickerData.PickerTemplate.ViewFields.Fields)
            {
                Type t1 = Type.GetType(vfield.FieldType);

                resultsTable.Columns.Add(vfield.Name, t1);
            }
            //
            // 2. Fill it with data
            //
            PickerDataService service = new PickerDataService(PickerSearchDialog.Picker
                .PickerData.PickerTemplate);
            string query = String.Format(@"{0} like '{1}%'", groupName, search);

            DataTable qTable = service.Query(query);

            ConvertToResult(qTable, resultsTable);
            // Return results
            this.PickerDialog.Results = resultsTable;
            if (resultsTable.Rows.Count == 0)
            {
                if (String.IsNullOrEmpty(search))
                {
                    this.PickerDialog.ErrorMessage = "Empty search text";
                }
                else
                {
                    this.PickerDialog.ErrorMessage = "No matching records found.";
                }
            }
            return resultsTable.Rows.Count;
        }

        private void ConvertToResult(DataTable sourceTable, DataTable resultsTable)
        { 
            foreach(DataRow row in sourceTable.Rows)
            {                    
                DataRow newRow = resultsTable.NewRow();
                foreach (DataColumn col in resultsTable.Columns)
                {
                    newRow[col.ColumnName] = row[col.ColumnName];
                }
                resultsTable.Rows.Add(newRow);
            }
        }
    }

}
